<template>
  <div class="upload">
    <div v-if="!isPic" class="upload-block" @click="uploadFile">
      <el-icon :size="20"><plus /></el-icon>
      点击打开图片
    </div>
    <el-tooltip v-else content="重新选择" placement="top">
      <img  class="upload-img" :src="src" alt="" @click="isPic = false">
    </el-tooltip>

    <el-button :disabled="!isPic" @click="doUpload">确认上传</el-button>
  </div>

  <input type="file" id="upload-block-real-input" style="display: none" accept="image/gif,image/jpeg,image/jpg,image/png">
</template>

<script>
import {Plus} from '@element-plus/icons'
import {uploadImage} from "../../utils/http/files";
import {User} from '../../utils/http/user';

export default {
  name: "FaviconUpload",
  components:{
    Plus
  },
  emits:['closeModal'],
  data:function (){
    return {
      reader  : {},
      src :'',
      isPic : false
    }
  },
  mounted() {
    this.reader = document.getElementById('upload-block-real-input')
    this.reader.onchange = ()=>{
      let file = this.reader.files[0]
      if (file.size > 1024*1024*2){
        this.$error('文件大小不能超过2m')
        return
      }
      let rd = new FileReader()
      rd.readAsDataURL(file)
      rd.onload = (e)=>{
        let imageFile = e.target.result;
        this.src = imageFile;
        this.isPic = true;
      }
    }
  },
  methods:{
    uploadFile(){
      this.reader.click()
    },
    async doUpload(){
      let file = this.reader.files[0]
      this.$warning('免费图床速度慢，请稍后',5000)
      let resp = await uploadImage(file)
      if (!resp.success){
        this.$error('上传失败，'+resp.message)
      }else {
        console.log(resp)
        let info = this.$store.state.userInfo;
        info.favicon = resp.url;
        let resp2 = await User.changeUserInfo({favicon:resp.url})
        if (resp2.success){
          this.$success('修改成功')
          localStorage.info = JSON.stringify(info)
          this.$store.commit('updateInfo',info)
          this.$emit('closeModal')
        }else {
          this.$error(resp2.message)
        }
      }
    }
  }
}
</script>

<style scoped>
.upload{
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.upload-block{
  width: 120px;
  height: 120px;
  border: 2px dashed #53a8ff;
  border-radius: 10px;
  margin-bottom: 20px;
  color: #53a8ff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.upload-img{
  width: 120px;
  height: 120px;
  margin-bottom: 20px;
  cursor: pointer;
}
</style>